package ru.amse.jsynchro.kernel.task;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ru.amse.jsynchro.fileSystem.FileSystem;
import ru.amse.jsynchro.kernel.Difference;
import ru.amse.jsynchro.kernel.Operation;
import ru.amse.jsynchro.logging.ILogger;

/**
 * Task implements action, which consists
 * in effective copying of the first folder to
 *  the second one. Resulting folder must be identical
 *  with the first one.
 * 
 * @author miha
 *
 */
public class DirectedDelTask extends Task {
    protected List<Difference> secondDiffs;
    
    public DirectedDelTask(String firstFolder, FileSystem fs1, 
                           String secondFolder, FileSystem fs2, 
                           boolean forceResolveConflicts, ILogger logger) throws IOException {
        super(firstFolder, fs1, secondFolder, fs2, forceResolveConflicts, logger);
    }
    
    public boolean analyze() {
        secondDiffs = first.compare(second, true);
        combineAtomic();
        return getDiffsNumber() > 0;
    }

    protected void combineAtomic() {
        List<Difference> atomic = new ArrayList<Difference>();
        for (Difference d: secondDiffs) {
            if (d.getOperation() == Operation.ADD) {
                first.addAtomicDiff(d, atomic, false);
            } else {
                second.addAtomicDiff(d, atomic, true);
            }
        }
        secondDiffs = atomic;
    }
    
    public void synchronize() {
        applyChanges(secondDiffs, first, second);
    }
    
    protected void resolveConflicts() {
        // TODO may be needed in future
        
    }
    
    public int getDiffsNumber() {
        return secondDiffs.size();
    }
    
    public List<String> getStringDifferences() {
        
        List<String> result = new ArrayList<String>();
        
        for (Difference d: secondDiffs) {
            if (d.getOperation() != Operation.NOTHING) {
                result.add(second.getPath() + File.separator + d.toString());
            }
        }
        return result;
    }
}
